package com.wmwj.hxlj.service.impl;

import com.wmwj.hxlj.entity.User;
import com.wmwj.hxlj.entity.Video;
import com.wmwj.hxlj.mapper.UserMapper;
import com.wmwj.hxlj.mapper.VideoMapper;
import com.wmwj.hxlj.service.VideoService;
import com.wmwj.hxlj.utils.Result;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.UUID;

@Service
public class VideoServiceImpl implements VideoService {

    @Autowired
    private VideoMapper videoMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Result<String> uploadVideo(Long userId, String title, MultipartFile file) {

        if(file.isEmpty()){
            throw new RuntimeException("上传文件为空");
        }

        if (!file.getContentType().startsWith("video/")) {
            throw new RuntimeException("只能上传视频格式文件");
        }

        if(file.getSize() > 1024*1024*300){
            throw new RuntimeException("文件大小不能超过300M");
        }

        Video video = new Video();
        video.setUserId(userId);
        video.setTitle(title);
        //通过作者id查询是否存在
        User user = userMapper.findById(video.getUserId());
        if (user == null)
            throw new RuntimeException("用户不存在");

        try {
            // 获取文件后缀
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename()
                    .lastIndexOf(".")+1);
            // 生成随机文件名
            String fileName = UUID.randomUUID().toString() + "." + suffix;

            // 本地文件存储地址
            String filePath = "H:\\workspace\\data\\video\\" + fileName;
            File destFile = new File(filePath);
            if (!destFile.getParentFile().exists()){
                destFile.getParentFile().mkdirs();
            }
            file.transferTo(destFile);

            String coverPath;

            try (FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(destFile)) {
                grabber.start();

                // 跳转到视频的10秒处（精确到微秒）
                grabber.setTimestamp(10_000_000);

                // 从视频中提取当前帧并保存为图片
                Frame frame = grabber.grabImage();
                // 生成封面图片的保存路径，使用UUID确保文件名唯一
                coverPath = "H:\\workspace\\data\\videoCover\\" + UUID.randomUUID() + ".jpg";

                // 创建Java2DFrameConverter对象，用于将Frame对象转换为BufferedImage对象
                Java2DFrameConverter converter = new Java2DFrameConverter();

                // 将抓取的帧图像转换为BufferedImage对象
                BufferedImage image = converter.convert(frame);

                // 将BufferedImage对象保存为JPEG格式的图片文件
                ImageIO.write(image, "jpg", new File(coverPath));
                grabber.stop();
            }

            //在数据库中保存视频信息
            video.setUrl(filePath);
            video.setCover(coverPath);
            video.setUuid(UUID.randomUUID().toString());
            video.setAuthor(user.getNickName());
            videoMapper.insert(video);

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("上传视频失败");
        }

        return Result.success("上传成功");
    }
}
